package com.kitty.game.activity.service.time;

import com.kitty.common.cache.RedisService;
import com.kitty.common.core.SchedulerManager;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.base.service.BagService;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.Position;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.house.HouseController;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.common.model.Reason;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 战神处理类
 */
@Component
public class CaiShenHandler extends FightActivityHandler {
    Logger logger = LoggerFactory.getLogger(HouseController.class);
    /**
     * 天墉城、无名小镇和东海渔村
     */
    private static final List<Integer> MAPIDS = Arrays.asList(7000);
    @Autowired
    FightService fightService;
    @Autowired
    RedisService redisService;
    /**
     * 财神npc显示名称
     */
    private static final String NAME = "财神";
    private static final List<String> SMALL_BOSS_NAME = Arrays.asList("功夫龙", "功夫龙", "财气猪", "财气猪", "精灵鼠","精灵鼠","宠物狗","宠物狗","宠物狗");
    /**
     * 财神icon
     */
    private static final int ICON = 6236;
    /**
     * 财神持续时间，单位毫秒
     */
    //private static final long NPC_CONTINUED_TIME = 1 * TimeUtil.ONE_MINUTE;
    private static final String CONTENT = "那些讨厌的精灵鼠总是偷我的宝贝，\n你能帮我对付他们的话，我会论功行赏！\n#R战斗结束时死亡的角色会受到惩罚。#n[对付偷宝贝的精灵鼠/" + NpcButton.FIGHT_TO_CAISHEN.getKey() + "][离开]";

    private static final String PIRATE_COME_NUMOR = "听说在#Z风月谷#Z有携带大量财物的财神下凡，大家快去寻找吧！";

    private static final String IN_FIGHT = "即使是神仙，也不能一次对付两个。[离开]";
    /**
     * 最少组队人数
     */
    private static final int MIN_TEAM_COUNT = 1;
    private static final String TEAM_COUNT_NOT_ENOUGH = "你还是凑齐三个人再来向我挑战吧！[离开]";
    private static final int ACCEPT_MIN_LEVEL = 40;
    private static final String TEAM_LEVEL_NOT_ENOUGH = "#Y{0}#n的等级还没有{1}级。[离开]";

    /**
     * 刷新财神，显示在对应的地图上
     */
    public void flushNpc() {
        /**先让之前刷新的攻城怪物消失*/
        hidePirate();
        /**
         * 刷新财神的数量
         */
        int num = Integer.parseInt(DataCache.REDIS_DATA.get("caishen_refresh_number"));
        for (int i = 0; i < num; i++) {
            /**随机地图*/
            int mapId = getRandomMapId();
            createNpc(mapId);
        }
        SpringUtils.getBean(ChatService.class).sendNumor(PIRATE_COME_NUMOR, Const.BRODCAST_MSG_TYPE_ROLE);
        //SchedulerManager.getInstance().schedule(() -> hidePirate(), NPC_CONTINUED_TIME);
    }

    /**使所有海盗在对应地图上消失*/
    public void hidePirate() {
        logger.warn("删除npc==财神");
        if (DataCache.CAISHEN_NPCS.size() > 0) {
            List<NPC> list = new ArrayList<>(DataCache.CAISHEN_NPCS.values());
            for (NPC npc : list) {
                if (npc.isInFight()) {
                    /**在战斗中隐藏*/
                    bossService.broadcastNpcHide(null, npc);
                } else {
                    clearPirate(npc);
                }
            }
        }
    }

    /**移除海盗*/
    private void clearPirate(NPC npc) {

        if (npc == null) {return ;}
        logger.debug("移除被消灭的财神=={}{}",npc.getId(),npc.getName());

        DataCache.CAISHEN_NPCS.remove(npc.getId());
        Set<Integer> set1 = DataCache.CAISHEN_MAP_NPC.get(npc.getMapId());
        if (set1 != null) {
            set1.remove(npc.getId());
        }
        removeUsedPosition(npc.getMapId(), npc.getX(), npc.getY());

        bossService.broadcastNpcHide(null, npc);
    }


    private int getRandomMapId() {
        int rand = ThreadLocalRandom.current().nextInt(MAPIDS.size());
        return MAPIDS.get(rand);
    }

    private void createNpc(int mapId) {
        Position position = getRandomPosition(mapId);

        NPC npc = new NPC();
        npc.setIcon(ICON);
        npc.setId(SpringUtils.getBean(NewBossService.class).getTempNpcId());
        npc.setX(position.getX());
        npc.setY(position.getY());
        npc.setFangxiang((short) new Random().nextInt(8));/*随机方向*/
        npc.setMapId(mapId);
        npc.setCreateTime(System.currentTimeMillis());
        //npc.setEndTime(npc.getCreateTime() + NPC_CONTINUED_TIME);
        npc.setType(NPC.TYPE_CAI_SHEN);
        npc.setContent(CONTENT);
        npc.setName(NAME);
        npc.setBossSetName(NAME);
        bossService.addTaskNpc(npc);
        bossService.broadcastNpcShow(null, npc);

        DataCache.CAISHEN_NPCS.put(npc.getId(), npc);

        Set<Integer> set = DataCache.CAISHEN_MAP_NPC.get(mapId);
        if (set == null) {
            set = new HashSet<>();
            DataCache.CAISHEN_MAP_NPC.put(mapId, set);
        }
        DataCache.CAISHEN_MAP_NPC.get(mapId).add(npc.getId());
    }
    @Override
    protected String getNpcContent(Role role, NPC bossNpc) {
        return null;
    }

    @Override
    protected String getNpcContentNotFight(Role role, NPC bossNpc) {
        /**检测是否在战斗中*/
        if (bossNpc.isInFight()) {
            return IN_FIGHT;
        }

        /**检测队伍人数*/
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return TEAM_COUNT_NOT_ENOUGH;
        }

        /**检测等级*/
        Team team = teamService.getTeam(role.getRoleId());
        String names = teamService.checkMember(team, memberRole -> memberRole.getLevel() < ACCEPT_MIN_LEVEL);
        if (names != null) {
            return MessageFormat.format(TEAM_LEVEL_NOT_ENOUGH, names, ACCEPT_MIN_LEVEL);
        }

        names = teamService.checkMember(team, memberRole -> getRoleRemainCount(memberRole) <= 0);
        if (names != null) {
            return "#R" + names + "#n没有挑战次数";
        }
        if (getRoleRemainCount(role) <= 0) {
            return "#R" + role.getName() + "#n没有挑战次数";
        }
        return null;
    }

    private byte getRoleRemainCount(Role role) {
        return (byte) SpringUtils.getActivityService().getRemainCount(role, ActivityType.caishen_ACTIVTY);
    }

    @Override
    protected void doStartFight(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = newBossParamList(role, bossNpc);
        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role));
        bossFightParam.setNpcId(bossNpc.getId());
        int maxRoleLevel = teamService.getMaxRoleLevelInTeam(role);
        bossFightParam.setNpcLevel((short) maxRoleLevel);
        Fight fight = bossService.startFightToBoss(role, bossFightParam);
    }

    private List<BossParam> newBossParamList(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = new ArrayList<>();
        int count = 10;

        /**npc对应的加在第1个*/
        BossSet bossSet = bossService.getBossSet(bossNpc.getBossSetName());
        bossSet.setQixue(Integer.MAX_VALUE);
        bossParamList.add(new BossParam(bossSet, bossNpc.getName(),true));
        List<String> nineBoss = getNineBoss();
        for (String boss : nineBoss) {
            bossSet = bossService.getBossSet(boss);
            bossParamList.add( new BossParam(bossSet, boss));
        }
        return bossParamList;
    }

    @Override
    protected int getFightType(Role role) {
        return Const.fightType_caiShen;
    }

//    @Override
//    protected NPC getBossNpc(int npcId) {
//        return SpringUtils.getMapService().getNpc(npcId);
//    }

    /**在战斗胜利后移除孔雀妖姬*/
    private void clearPirateAfterFightWin(NPC npc) {
        int oldPirateCount = DataCache.CAISHEN_NPCS.size();
        /**移除孔雀妖姬操作*/
        clearPirate(npc);
        int newPirateCount = DataCache.CAISHEN_NPCS.size();

        if (newPirateCount != oldPirateCount) {
            if (newPirateCount > 0) {
                /**不是最后一个时，发的谣言*/
                //String msg = MessageFormat.format(KILL_MESSAGE, newPirateCount);
                //SpringUtils.getChatService().sendNumor(msg, Const.BRODCAST_MSG_TYPE_ROLE);
            } else {
                /**杀死最后一个时，发的谣言*/
                //if (oldPirateCount == 1 && newPirateCount == 0) {
                //SpringUtils.getChatService().sendNumor(PIRATE_ALL_KILL_NUMOR, Const.BRODCAST_MSG_TYPE_ROLE);
                // }
            }
        }
    }
    @Override
    protected NPC getBossNpc(int npcId) {
        return DataCache.CAISHEN_NPCS.get(npcId);
    }
//    @Override
//    protected void clearNpcAfterWin(Role role, NPC bossNpc) {
//        clearNpc(bossNpc);
//    }
@Override
protected void clearNpcAfterWin(Role role, NPC bossNpc) {
    clearPirateAfterFightWin(bossNpc);
}
    private void clearNpc(NPC npc) {
        if (npc == null) {
            return;
        }

        bossService.delTaskNpc(npc);
        removeUsedPosition(npc.getMapId(), npc.getX(), npc.getY());
        bossService.broadcastNpcHide(null, npc);
    }

    /**
     * 这里可以写单独的处理
     * @param role
     * @param fightEndEvent
     * @param bossNpc
     */
    @Override
    protected void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        SpringUtils.getActivityService().addFinishCount(role, ActivityType.caishen_ACTIVTY, 1);
        NutMap reward = fightEndEvent.getReward();
        double rewardNumber = reward.getDouble("reward_number",0);
        /**道行武学奖励*/
        int exp = role.getLevel() * reward.getInt("rewardExp", 0);
        int daohang = reward.getInt("rewardDaohang", 0) * role.getLevel();
        int petWuxue = reward.getInt("petRewardWuxue", 0) * role.getLevel();
        RoleService roleService = SpringUtils.getRoleService();
        roleService.addTao(role, daohang);
        int currPetId = role.getTempCache("fight_current_pet_id", 0);
        Pet pet = SpringUtils.getPetService().getPetById(currPetId, role);
        if (pet != null) {
            roleService.addPetMatiral(role, pet, petWuxue);
        }
        roleService.addExp(role,exp,role.getLevel(),currPetId);

        // 奖励装备
        short roleLevel = role.getLevel();
        String temp = roleLevel + "";
        if (temp.length() == 3) {
            roleLevel = Short.parseShort(temp.substring(0, 2) + 0);
        } else {
            roleLevel = Short.parseShort(temp.substring(0, 1) + 0);
        }

        BagService bagService = SpringUtils.getBean(BagService.class);
        EquipService equipService = SpringUtils.getBean(EquipService.class);

        short newPos = bagService.getPos(role, false);
        if (newPos > 0) {
            equipService.getNotIdentifyEquip(roleLevel, role, newPos);
        } else {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("背包已满，请整理背包"));
            return;
        }
        int caishen_jifen = Integer.parseInt(DataCache.REDIS_DATA.get("caishen_jifen"));
        int caishen_jinyuanbao = Integer.parseInt(DataCache.REDIS_DATA.get("caishen_jinyuanbao"));
        int caishen_yinyuanbao = Integer.parseInt(DataCache.REDIS_DATA.get("caishen_yinyuanbao"));
        if(caishen_jifen>0){
            caishen_jifen =  (int)(caishen_jifen*rewardNumber);
            roleService.addRechargeScore(role, caishen_jifen);
        }
        if(caishen_jinyuanbao>0){
            caishen_jinyuanbao =  (int)(caishen_jinyuanbao*rewardNumber);
            roleService.addGold(role, caishen_jinyuanbao, Reason.CAI_SHEN);
        }
        if(caishen_yinyuanbao>0){
            caishen_yinyuanbao =  (int)(caishen_yinyuanbao*rewardNumber);
            roleService.addSiver(role, caishen_yinyuanbao, Reason.CAI_SHEN);
        }
        fightService.sendBossExtReward(role,fightEndEvent);


    }

    @Override
    protected void clearNpcTimeOut(NPC npc) {
        clearNpc(npc);
    }

    @Override
    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        super.doFightFail(role, fightEndEvent);

        teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
    }
    public List<String> getNineBoss(){
        List<String> smallBossName = new ArrayList();
        List<String> names =  new ArrayList();
        names.add("功夫龙");
        names.add("功夫龙");
        names.add("财气猪");
        names.add("财气猪");
        names.add("精灵鼠");
        names.add("精灵鼠");
        names.add("宠物狗");
        names.add("宠物狗");
        names.add("宠物狗");
        for (int i = 0; i < 9; i++) {
            int x = ThreadLocalRandom.current().nextInt(names.size());
            String s = names.get(x);
            smallBossName.add(s);
            names.remove(x);
        }
        return smallBossName;
    }

    public static void main(String[] args) {

    }
}
